package com.ydd.common.filter;


import com.ydd.common.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class JwtTokenFilter extends OncePerRequestFilter implements Ordered {
    @Autowired
    private JwtUtil jwtUtils;

    public JwtTokenFilter() {
        ArrayList<String> apiList = new ArrayList<>();
        apiList.add("/login");
        apiList.add("/register");
        apiList.add("/openApi");//登录注册和openApi不需要验证
        this.API = apiList;
    }

    private final List<String> API;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        String authorization = request.getHeader("Authorization");
        String requestURI = request.getRequestURI();
        log.info("接口地址: {}--ip: {}",requestURI,ip);
        for (String api : API) {
            if (requestURI.contains(api)) {//api接口不用校验token
                filterChain.doFilter(request, response);
                return;
            }
        }

        try {
            // 校验token
            jwtUtils.verifyToken(authorization);
        } catch (Exception e) {
            extracted(response, "token验证失败");
            return; // 结束过滤器链
        }

        filterChain.doFilter(request, response);
    }

    private void extracted(HttpServletResponse response, String msg) throws IOException {
        response.setStatus(200); // 设置响应状态码
        response.setContentType(MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8"); // 指定UTF-8字符集
        PrintWriter out = response.getWriter();
        String result = String.format("{\"code\":%d,\"msg\":\"%s\"}", 500, msg);
        out.print(result); // 将错误信息转换为JSON并写入响应
        out.flush();
    }


    @Override
    public int getOrder() {
        return 2;
    }
}